package com.cpi.basilos.unit.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;

import com.cpi.basilos.unit.converter.UnitConverter;
import com.cpi.basilos.unit.dao.UnitDAO;
import com.cpi.basilos.unit.dto.UnitByOriginDTO;
import com.cpi.basilos.unit.exception.UnitException;
import com.cpi.basilos.unit.view.UnitTransitView;
import com.cpi.basilos.unit.view.UnitView;
import com.cs.common.exception.CSException;
import com.cs.common.utils.NumberUtil;

public class UnitService {
	private static org.apache.log4j.Logger logger = Logger.getLogger(UnitService.class);
	public UnitTransitView getTransitByOrigin(int warehouseId)throws UnitException{
		List unitViews =  null;
		List unitTransitDTOs = null;
		UnitDAO unitDAO = null;
		UnitByOriginDTO unitByOriginDTO = null;
		UnitTransitView unitTransitView = null;
		UnitView unitView = null;
		UnitConverter unitConverter = null;
		Iterator itTransitDTOs = null;
		double totalTransit = 0;
		try{
			unitTransitView = new UnitTransitView();
			unitConverter = new UnitConverter();
			unitDAO = new UnitDAO();
			unitTransitDTOs = unitDAO.getTransitByOrigin(warehouseId);
			unitViews = new ArrayList(unitTransitDTOs.size());
			itTransitDTOs = unitTransitDTOs.iterator();
			while(itTransitDTOs.hasNext()){
				unitByOriginDTO = (UnitByOriginDTO)itTransitDTOs.next();
				totalTransit += unitByOriginDTO.getAmount();
				unitView = unitConverter.convertUnitByOriginDTOToView(unitByOriginDTO);
				unitViews.add(unitView);
			}
			unitTransitView.setUnitViews(unitViews);
			unitTransitView.setTotalTransit(NumberUtil.convertQuantity(totalTransit));
		}catch(UnitException unitException){
			throw unitException;
		}catch(Exception exception){
			UnitException unitException = null;
			exception.printStackTrace(System.out);
			logger.error(exception);
			unitException = new UnitException(exception, CSException.LAYER_SERVICE, CSException.ACTION_SELECT);
			throw unitException;
		}
		return unitTransitView;
	}
	
	public List getTransits(int warehouseId)throws UnitException{
		List unitViews = null;
		List unitDTOs = null;
		UnitDAO unitDAO = null;
		UnitConverter unitConverter = null;
		try{
			unitDAO = new UnitDAO();
			unitConverter = new UnitConverter();
			unitDTOs = unitDAO.getTransit(warehouseId);
			unitViews = unitConverter.convertUnitDTOsToViews(unitDTOs);
		}catch(UnitException unitException){
			throw unitException;
		}catch(Exception exception){
			UnitException unitException = null;
			exception.printStackTrace(System.out);
			logger.error(exception);
			unitException = new UnitException(exception, CSException.LAYER_SERVICE, CSException.ACTION_SELECT);
			throw unitException;
		}
		return unitViews;
	}
}